<template>
  <view class="red-packet-container">
    <!-- 顶部区域 - 改为圆弧底部设计 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <FeatherIcon name="chevron-left" size="24" color="#fff" />
      </view>
      <text class="title">红包详情</text>
      <view class="placeholder"></view>
    </view>

    <!-- 红包信息区域 - 整体居中布局 -->
    <view class="red-packet-info">
      <image
        class="sender-avatar"
        :src="
          redPacketData.userAvatarURL ||
          'https://file.fishpi.cn/default-avatar.png'
        "
        mode="aspectFill"
      ></image>
      <view class="sender-info">
        <view class="sender-name">{{
          redPacketData.userName || "未知用户"
        }}</view>
        <view class="red-packet-type">{{
          redPacketData.msg || "恭喜发财，大吉大利"
        }}</view>
      </view>

      <!-- 显示用户抢红包结果 -->
      <view
        class="user-result"
        v-if="
          hasProcessedResult &&
          redPacketData.type !== 'rockPaperScissors' &&
          userGotPacket
        "
      >
        <text class="success-text">{{ userPacketAmount }} 积分</text>
      </view>

      <!-- 猜拳红包结果显示 - 对所有用户可见 -->
      <view class="rps-result" v-if="redPacketType === 'rockPaperScissors'">
        <view class="rps-result-item" v-if="recordList.length > 0">
          <view class="rps-status-icon">
            <text v-if="recordList[0].userMoney > 0">🎯</text>
            <text v-else-if="recordList[0].userMoney < 0">💔</text>
            <text v-else>🤝</text>
          </view>
          <text v-if="recordList[0].userMoney > 0" class="win-text"
            >{{ recordList[0].userName }} 赢了！手气爆棚，老板手抖了？</text
          >
          <text v-else-if="recordList[0].userMoney < 0" class="lose-text"
            >{{ recordList[0].userName }} 输了...看来今天走路没看黄历</text
          >
          <text v-else class="draw-text"
            >{{ recordList[0].userName }} 平局，至少没输，可以喝口水压压惊</text
          >
        </view>
        <view class="rps-result-item" v-else>
          <text class="rps-waiting">石头剪刀布，看看谁的手气好！</text>
        </view>
      </view>

      <!-- 用户个人猜拳结果 - 仅在猜拳红包时显示 -->
      <view
        class="user-rps-result"
        v-if="redPacketType === 'rockPaperScissors' && userGotPacket"
      >
        <view class="user-rps-avatar">
          <image
            :src="
              currentUser?.userAvatarURL ||
              'https://file.fishpi.cn/default-avatar.png'
            "
            mode="aspectFill"
          ></image>
        </view>
        <text v-if="userPacketAmount > 0" class="user-win-text"
          >你赢了 +{{ userPacketAmount }} 积分</text
        >
        <text v-else-if="userPacketAmount < 0" class="user-lose-text"
          >你输了 {{ userPacketAmount }} 积分</text
        >
        <text v-else class="user-draw-text">平局 +0 积分</text>
      </view>

      <!-- 红包状态提示 -->
      <view class="packet-status">
        <block v-if="redPacketType === 'rockPaperScissors'">
          <text>{{ hasProcessedResult ? "红包已被抢完" : "等待抢红包" }}</text>
        </block>
        <block v-else-if="redPacketType === 'heartbeat'">
          <text>{{
            hasProcessedResult ? "心跳红包已领完" : "心跳红包，手气看人品"
          }}</text>
        </block>
        <block v-else>
          {{
            userGotPacket
              ? "红包已领取"
              : hasProcessedResult
              ? "红包已领完"
              : "红包详情"
          }}
        </block>
      </view>
    </view>

    <!-- 底部记录区域 -->
    <view class="record-section">
      <view class="record-title">
        <text>领取记录</text>
        <text class="record-count"
          >{{ redPacketData.gotCount || 0 }}/{{
            redPacketData.totalCount || redPacketData.count || 1
          }}</text
        >
      </view>

      <view v-if="loading" class="loading">
        <view class="loading-dot"></view>
        <view class="loading-dot"></view>
        <view class="loading-dot"></view>
      </view>

      <scroll-view
        v-else
        class="record-list"
        scroll-y
        @scrolltolower="onScrollToLower"
      >
        <view
          class="record-item"
          v-for="(record, index) in displayRecords"
          :key="index"
          :class="{
            'current-user': isCurrentUser(record.userName),
            'best-luck': isBestLuck(record, index),
            'worst-luck': isWorstLuck(record, index),
          }"
        >
          <view class="record-user">
            <image
              class="record-avatar"
              :src="
                record.avatar ||
                record.userAvatarURL ||
                'https://file.fishpi.cn/default-avatar.png'
              "
              mode="aspectFill"
            ></image>
            <view class="record-user-info">
              <text class="record-username">{{ record.userName }}</text>
              <text class="record-time">{{
                formatRecordTime(record.time)
              }}</text>
            </view>
          </view>
          <view class="record-amount-wrapper">
            <view
              class="record-amount"
              :class="{
                'negative-amount': Number(record.userMoney) < 0,
              }"
            >
              {{ record.userMoney || record.amount || 0 }}
              <text class="record-unit">积分</text>
            </view>
            <view class="tag-wrapper">
              <view class="lucky-icon" v-if="isBestLuck(record, index)"
                >🌟手气王</view
              >
              <view class="unlucky-icon" v-if="isWorstLuck(record, index)"
                >💔手气差</view
              >
            </view>
          </view>
        </view>

        <view v-if="recordList.length === 0" class="no-records">
          <text>暂无领取记录</text>
        </view>

        <!-- 加载更多指示器 -->
        <view
          v-if="hasMoreRecords && !loadingMore"
          class="load-more"
          @click="loadMoreRecords"
        >
          <text>查看更多</text>
        </view>

        <view v-if="loadingMore" class="loading-more">
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
          <view class="loading-dot"></view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import FeatherIcon from "@/components/FeatherIcon.vue";
import { showLoading, hideLoading, showError } from "@/utils/common.js";
import api from "@/api";

// 状态变量
const redPacketData = ref({});
const recordList = ref([]);
const loading = ref(true);
const redPacketId = ref("");
const redPacketType = ref("");
const currentUser = ref(null);
const userGotPacket = ref(false);
const userPacketAmount = ref(0);
const hasProcessedResult = ref(false);

// 添加分页处理相关变量
const PAGE_SIZE = 10; // 每页显示的记录数
const currentPage = ref(1);
const loadingMore = ref(false);

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const res = await api.user.getCurrentUser();
    if (res.code === 0) {
      currentUser.value = res.data;
      console.log("当前用户信息:", currentUser.value);
    }
  } catch (e) {
    console.error("获取当前用户信息失败:", e);
  }
};

// 判断是否为当前用户
const isCurrentUser = (userName) => {
  return currentUser.value && currentUser.value.userName === userName;
};

// 检查当前用户是否抢到红包
const checkUserGotPacket = () => {
  if (!currentUser.value || !recordList.value.length) return;

  const userRecord = recordList.value.find(
    (record) => record.userName === currentUser.value.userName
  );

  if (userRecord) {
    userGotPacket.value = true;
    userPacketAmount.value = userRecord.userMoney || userRecord.amount || 0;
  } else {
    userGotPacket.value = false;
    userPacketAmount.value = 0;
  }

  // 判断红包是否已领完，只有在以下情况设置hasProcessedResult为true:
  // 1. 红包数量已领完 (gotCount >= totalCount)
  // 2. 当前用户已领取红包
  if (redPacketData.value.got >= redPacketData.value.count) {
    hasProcessedResult.value = true;
  }

  console.log(
    "用户抢红包结果:",
    userGotPacket.value ? "抢到了" : "未抢到",
    userPacketAmount.value,
    "红包状态:",
    hasProcessedResult.value ? "已领完" : "未领完"
  );
};

// 页面加载时获取红包数据
onMounted(async () => {
  // 获取当前用户信息
  await fetchCurrentUser();

  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.$page.options || {};

  // 从页面参数获取红包ID
  redPacketId.value = options.id || "";
  redPacketType.value = options.type || "";
  console.log("红包类型:", options.type);
  // 从页面参数获取红包数据(兼容H5环境或缓存失败的情况)
  const packetData = options.data || "";
  if (packetData) {
    try {
      // 解析从聊天页面传过来的红包数据
      const data = JSON.parse(decodeURIComponent(packetData));
      console.log("从URL获取到红包数据:", data);

      // 处理红包数据
      processRedPacketData(data);
    } catch (e) {
      console.error("解析红包数据失败:", e);
      showError("解析红包数据失败");
      setTimeout(() => {
        goBack();
      }, 1500);
    }
  } else {
    showError("红包参数错误");
    setTimeout(() => {
      goBack();
    }, 1500);
  }
});

// 计算当前显示的记录
const displayRecords = computed(() => {
  return recordList.value.slice(0, currentPage.value * PAGE_SIZE);
});

// 计算是否还有更多记录
const hasMoreRecords = computed(() => {
  return displayRecords.value.length < recordList.value.length;
});

// 加载更多记录
const loadMoreRecords = async () => {
  if (!hasMoreRecords.value || loadingMore.value) return;

  loadingMore.value = true;

  // 模拟网络请求延迟
  await new Promise((resolve) => setTimeout(resolve, 500));

  currentPage.value++;
  loadingMore.value = false;
};

// 添加检测是否为H5环境的函数
const isH5 = () => {
  // #ifdef H5
  return true;
  // #endif
  return false;
};

// 监听滚动到底部事件 - H5环境下自动加载更多
const onScrollToLower = () => {
  // 仅在H5环境下自动加载更多
  if (isH5()) {
    loadMoreRecords();
  }
  // APP环境通过点击"查看更多"按钮加载
};

// 重置分页状态
const resetPagination = () => {
  currentPage.value = 1;
  loadingMore.value = false;
};

// 处理红包数据
// 处理红包数据函数的优化处理：
const processRedPacketData = (data) => {
  if (!data) {
    loading.value = false;
    return;
  }

  try {
    // 重置分页状态
    resetPagination();

    // 解析数据 - 兼容两种数据格式
    const who = data.who || [];
    const info = data.info || {};

    // 如果数据是直接的红包对象（不是嵌套的）
    if (!data.who && !data.info && data.oId) {
      // 直接使用传入的红包数据
      redPacketData.value = {
        ...data,
        userAvatarURL:
          data.userAvatarURL || "https://file.fishpi.cn/default-avatar.png",
        userName: data.userName || "未知用户",
        msg: data.msg || "恭喜发财，大吉大利",
        type: data.type || "random", // 添加红包类型
      };

      // 设置领取记录
      if (data.got && Array.isArray(data.got)) {
        recordList.value = data.got.map((item) => ({
          userName: item.userName,
          userId: item.userId,
          avatar:
            item.avatar ||
            item.userAvatarURL ||
            "https://file.fishpi.cn/default-avatar.png",
          userMoney: item.userMoney,
          time: item.time || new Date().toISOString(),
        }));
      } else if (data.who && Array.isArray(data.who)) {
        recordList.value = data.who.map((item) => ({
          userName: item.userName,
          userId: item.userId,
          avatar:
            item.avatar ||
            item.userAvatarURL ||
            "https://file.fishpi.cn/default-avatar.png",
          userMoney: item.userMoney,
          time: item.time || new Date().toISOString(),
        }));
      }

      // 设置已领取数量
      redPacketData.value.gotCount = recordList.value.length;
      redPacketData.value.totalCount =
        data.count || data.totalCount || recordList.value.length;

      // 计算红包总金额
      redPacketData.value.totalAmount = recordList.value.reduce(
        (total, item) => {
          return total + (Number(item.userMoney) || 0);
        },
        0
      );

      // 检查用户是否抢到红包
      checkUserGotPacket();

      loading.value = false;
      return;
    }

    // 处理标准格式数据
    if (info) {
      redPacketData.value = {
        ...info,
        userAvatarURL:
          info.userAvatarURL || "https://file.fishpi.cn/default-avatar.png",
        userName: info.userName || "未知用户",
        msg: info.msg || "恭喜发财，大吉大利",
        type: info.type || "random", // 添加红包类型
      };
    }

    // 设置领取记录
    if (who && Array.isArray(who)) {
      recordList.value = who.map((item) => ({
        userName: item.userName,
        userId: item.userId,
        avatar:
          item.avatar ||
          item.userAvatarURL ||
          "https://file.fishpi.cn/default-avatar.png",
        userMoney: item.userMoney,
        time: item.time || new Date().toISOString(),
      }));

      // 设置已领取数量
      redPacketData.value.gotCount = recordList.value.length;
      redPacketData.value.totalCount = info.count || recordList.value.length;

      // 计算红包总金额
      redPacketData.value.totalAmount = recordList.value.reduce(
        (total, item) => {
          return total + (Number(item.userMoney) || 0);
        },
        0
      );

      // 检查用户是否抢到红包
      checkUserGotPacket();
    }
  } catch (e) {
    console.error("处理红包数据失败:", e);
  } finally {
    loading.value = false;
  }
};

// 格式化领取记录时间
const formatRecordTime = (timeStr) => {
  if (!timeStr) return "";

  try {
    // 处理格式为 "2025-05-06 15:57:43" 的时间字符串
    if (timeStr.includes(" ")) {
      const parts = timeStr.split(" ");
      const dateParts = parts[0].split("-");
      const timeParts = parts[1].split(":");

      if (dateParts.length === 3 && timeParts.length === 3) {
        // 返回类似于 "5-5 22:58" 的格式
        return `${dateParts[1]}-${dateParts[2]} ${timeParts[0]}:${timeParts[1]}`;
      }
    }

    // 处理其他格式
    const date = new Date(timeStr);
    return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date
      .getMinutes()
      .toString()
      .padStart(2, "0")}`;
  } catch (e) {
    return timeStr;
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 判断是否为手气最佳（积分最多）
const isBestLuck = (record, index) => {
  if (recordList.value.length <= 1) return false;

  // 对于普通红包，积分最高者为手气王
  if (redPacketType.value !== "heartbeat") {
    return (
      record.userMoney ===
      Math.max(...recordList.value.map((r) => Number(r.userMoney || 0)))
    );
  }

  // 对于心跳红包，正积分最高者为手气王
  const positiveRecords = recordList.value.filter(
    (r) => Number(r.userMoney || 0) > 0
  );
  if (positiveRecords.length === 0) return false;

  const maxPositive = Math.max(
    ...positiveRecords.map((r) => Number(r.userMoney || 0))
  );
  return Number(record.userMoney || 0) === maxPositive && maxPositive > 0;
};

// 判断是否为手气最差（心跳红包中负积分最多）
const isWorstLuck = (record, index) => {
  if (recordList.value.length <= 1 || redPacketType.value !== "heartbeat")
    return false;

  // 只在心跳红包中判断
  const negativeRecords = recordList.value.filter(
    (r) => Number(r.userMoney || 0) < 0
  );
  if (negativeRecords.length === 0) return false;

  const minNegative = Math.min(
    ...negativeRecords.map((r) => Number(r.userMoney || 0))
  );
  return Number(record.userMoney || 0) === minNegative;
};
</script>

<style lang="scss">
.red-packet-container {
  min-height: 100vh;
  background-color: #f7f7f7;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-top: 60rpx;
  padding-bottom: 80rpx;
  background: #ff5050;
  position: relative;
  border-radius: 0 0 30% 30% / 0 0 20% 20%;

  .back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1;
  }

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .placeholder {
    width: 60rpx;
  }
}

.red-packet-info {
  background: #fff;
  margin: -60rpx 30rpx 20rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 2;

  .sender-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    border: 4rpx solid rgba(255, 80, 80, 0.2);
    margin-bottom: 20rpx;
  }

  .sender-info {
    text-align: center;
    margin-bottom: 20rpx;
  }

  .sender-name {
    font-size: 34rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
  }

  .red-packet-type {
    font-size: 28rpx;
    color: #666;
    text-align: center;
  }

  .user-result {
    margin: 30rpx 0;
    text-align: center;

    .success-text {
      font-size: 60rpx;
      font-weight: bold;
      color: #ff5050;
    }

    .best-luck-icon {
      margin-top: 10rpx;
      font-size: 40rpx;
    }
  }

  .packet-status {
    font-size: 28rpx;
    color: #999;
    margin-top: 10rpx;
    padding: 10rpx 20rpx;
    padding-top: 40rpx;
    border-top: 1px solid #f0f0f0;
    width: 100%;
    text-align: center;

    .win-text {
      color: #ff5050;
      font-weight: bold;
    }

    .lose-text {
      color: #999;
    }

    .draw-text {
      color: #ff9900;
    }
  }
}

.record-section {
  flex: 1;
  background-color: #fff;
  border-radius: 20rpx;
  margin: 0 30rpx 30rpx;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
  max-height: 750rpx;
}

.record-title {
  display: flex;
  justify-content: space-between;
  font-size: 30rpx;
  color: #333;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20rpx;
  font-weight: 500;

  .record-count {
    color: #666;
    font-weight: 500;
  }
}

.record-list {
  flex: 1;
  overflow-y: auto;
  height: 500rpx;
}

.record-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;

  &.current-user {
    background-color: rgba(255, 80, 80, 0.05);
    border-radius: 10rpx;
    padding: 20rpx 10rpx;
  }

  &.best-luck {
    background-color: rgba(255, 215, 0, 0.05);
  }

  &.worst-luck {
    background-color: rgba(0, 0, 0, 0.02);
  }
}

.record-user {
  display: flex;
  align-items: center;
  flex: 1;
}

.record-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

.record-user-info {
  display: flex;
  flex-direction: column;
}

.record-username {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.record-time {
  font-size: 24rpx;
  color: #999;
}

.record-amount-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.record-amount {
  font-size: 36rpx;
  color: #ff5050;
  font-weight: bold;

  &.negative-amount {
    color: #666;
  }

  .record-unit {
    font-size: 24rpx;
    color: #999;
    font-weight: normal;
    margin-left: 4rpx;
  }
}

.tag-wrapper {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-top: 6rpx;
}

.lucky-icon {
  font-size: 24rpx;
  color: #ff9900;
  background-color: rgba(255, 153, 0, 0.1);
  padding: 4rpx 10rpx;
  border-radius: 20rpx;
}

.unlucky-icon {
  font-size: 24rpx;
  color: #999;
  background-color: rgba(153, 153, 153, 0.1);
  padding: 4rpx 10rpx;
  border-radius: 20rpx;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;

  .loading-dot {
    width: 12rpx;
    height: 12rpx;
    background-color: #ff5050;
    border-radius: 50%;
    margin: 0 8rpx;
    animation: loading 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }

  @keyframes loading {
    0%,
    80%,
    100% {
      transform: scale(0);
    }
    40% {
      transform: scale(1);
    }
  }
}

.no-records {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 20rpx 0;
  color: #ff5050;
  font-size: 28rpx;
}

.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20rpx 0;

  .loading-dot {
    width: 8rpx;
    height: 8rpx;
    background-color: #ff5050;
    border-radius: 50%;
    margin: 0 6rpx;
    animation: loading 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }
  }
}

.rps-result {
  width: 100%;
  text-align: center;
  margin: 20rpx 0;

  .rps-result-item {
    padding: 16rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .rps-status-icon {
    font-size: 60rpx;
    margin-bottom: 10rpx;
  }

  .win-text {
    font-size: 34rpx;
    color: #ff5050;
    font-weight: bold;
  }

  .lose-text {
    font-size: 34rpx;
    color: #999;
  }

  .draw-text {
    font-size: 34rpx;
    color: #ff9900;
  }

  .rps-waiting {
    font-size: 34rpx;
    color: #666;
    font-weight: 500;
  }
}

.user-rps-result {
  margin: 20rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;

  .user-rps-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-bottom: 10rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .user-win-text {
    font-size: 40rpx;
    color: #ff5050;
    font-weight: bold;
  }

  .user-lose-text {
    font-size: 40rpx;
    color: #999;
  }

  .user-draw-text {
    font-size: 40rpx;
    color: #ff9900;
  }
}
</style>
